﻿@using System.ComponentModel.DataAnnotations
@using System.Text.Json
@using CodePlus.ApiGateway.Data.Logins
@using CodePlus.ApiGateway.Data.Ocelots

@inherits ModalTemplate<LoginInputDto>
@inject IJSRuntime JSRuntime
@inject IOcelotAdminService OcelotAdminService
@inject MessageService _message


<Form Model="@_model"
      LabelCol="new ColLayoutParam { Span = 4 }"
      WrapperCol="new ColLayoutParam { Span = 20 }"
      OnFinish="OnFinish"
      OnFinishFailed="OnFinishFailed">
    <FormItem Label="密钥">
        <InputPassword @bind-Value="@context.Password" />
    </FormItem>
    <FormItem WrapperCol="new ColLayoutParam{ Offset = 10, Span = 4 }">
        <Button Type="@ButtonType.Primary" HtmlType="submit" Loading="@_loading">
            登录
        </Button>
    </FormItem>
</Form>

<br />
<br />


@code{


    private LoginInputDto _model;

    private bool _loading = false;


    protected override void OnInitialized()
    {
        _model = base.Options ?? new LoginInputDto();
        base.OnInitialized();
    }

    private async Task OnFinish(EditContext editContext)
    {
        _loading = true;
        Console.WriteLine($"Success:{JsonSerializer.Serialize(_model)}");
        try
        {
            var result = await OcelotAdminService.GetTokenAsync(_model);
            await JSRuntime.InvokeVoidAsync(
            "gatewayJsFunctions.setCookies",
            "AccessToken", result.AccessToken, 30);
            _ = base.ModalRef.CloseAsync();
        }
        catch (Exception ex)
        {
            _message.Error(ex.InnerException.Message);
        }
        finally
        {
            _loading = false;
        }

    }

    private void OnFinishFailed(EditContext editContext)
    {
        Console.WriteLine($"Failed:{JsonSerializer.Serialize(_model)}");
    }
}
